﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using SCFHS.Code;
using SCFHS.Data;
using System.Configuration;
using System.IO;

namespace SCFHS.Views
{
    public partial class Followup : SysBase
    {
        #region Definitions

        #endregion

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            string orderID = string.Empty;
            if (Request.QueryString["orderID"] != null)
                orderID = Request.QueryString["orderID"] as string;

            if (!string.IsNullOrEmpty(orderID) && !IsPostBack)
            {
                order = controller.SelectFullOrderInfo(int.Parse(orderID));
                if (order == null)
                {
                    lblMessage.Text = "عفوا رقم الطلب غير صحيح";
                    lblMessage.CssClass = "error";
                    return;
                }
                if (order.orderState == OrderStates.WaitingFollowUp || order.orderState == OrderStates.FollowUp || order.orderState == OrderStates.Instructions)
                {
                    hdfOrderNo.Value = order.orderID.ToString();
                    BindFollowupCatalog(order);
                }
                else
                {
                    lblMessage.Text = Messages.ProceudProcessField;
                    lblMessage.CssClass = "error";
                }
            }
        }

        protected void btnNextToOrder_Click(object sender, EventArgs e)
        {
            order = controller.SelectMainOrderInfo(txtOrderNumberToSearch.Text);
            if (order == null)
            {
                lblMessage.Text = "عفوا رقم الطلب غير صحيح";
                lblMessage.CssClass = "error";
                return;
            }
            if (order.orderState == OrderStates.WaitingFollowUp)
            {
                hdfOrderNo.Value = order.orderID.ToString();
                //order = controller.SelectFullOrderInfo(order.orderID);
                BindFollowupCatalog(order);
            }
            else
            {
                lblMessage.Text = Messages.ProceudProcessField;
                lblMessage.CssClass = "error";
            }
        }

        protected void btnAddFollowup_Click(object sender, EventArgs e)
        {
            SCFHS.Data.Followup followup = GetFollowupData();
            bool result = controller.AddOrderFollowUp(followup);
            if (!result)
            {
                lblMessage.Text = Messages.AddFollowupFail;
                lblMessage.CssClass = "error";
                return;
            }
            result = UpdateOrderState(OrderStates.FollowUp, followup.orderID);
            if (result)
            {
                lblMessage.Text = Messages.AddFollowupSuccess;
                lblMessage.CssClass = "info";
            }
            else
            {
                lblMessage.Text = Messages.AddFollowupFail;
                lblMessage.CssClass = "error";
            }

        }

        protected void btnUpdateOrder_Click(object sender, EventArgs e)
        {
            Instructions instruction = GetInstructionData();
            instruction.isFinalInstruction = false;

            //Insert instruction
            bool result = controller.AddOrderInstruction(instruction);
            if (!result)
            {
                lblMessage.Text = Messages.AddInstructionFail;
                lblMessage.CssClass = "error";
                return;
            }
            //Update order state
            result = UpdateOrderState(OrderStates.Instructions, instruction.orderID);
            if (result)
            {
                lblMessage.Text = Messages.AddInstructionSuccess;
                lblMessage.CssClass = "info";
            }

            lblMessage.Text = Messages.AddInstructionFail;
            lblMessage.CssClass = "error";

        }

        protected void btnSaveAndClose_Click(object sender, EventArgs e)
        {
            Instructions instruction = GetInstructionData();
            instruction.isFinalInstruction = true;

            //Insert instruction
            bool result = controller.AddOrderInstruction(instruction);
            if (result)
            {
                //Update order state
                result = UpdateOrderState(OrderStates.InstructionsAndDone, instruction.orderID);
                if (result)
                {
                    mView.ActiveViewIndex = 0;
                    lblMessage.Text = Messages.AddInstructionSuccess;
                    lblMessage.CssClass = "info";
                    return;
                }
            }

            lblMessage.Text = Messages.AddInstructionFail;
            lblMessage.CssClass = "error";
        }
        #endregion

        #region Helper Methods

        Instructions GetInstructionData()
        {
            Instructions instruction = new Instructions();
            instruction.instructionAuthority = txtAuthorityOf.Text;
            instruction.instruction = txtInstruction.Text;
            instruction.SubmitTimestamp = controller.ConvertDate(txtForwardDate.Text);
            instruction.orderID = int.Parse(hdfOrderNo.Value);
            return instruction;
        }

        SCFHS.Data.Followup GetFollowupData()
        {
            SCFHS.Data.Followup followup = new SCFHS.Data.Followup();
            followup.orderID = int.Parse(hdfOrderNo.Value);
            followup.followupFollowerName = txtFollowerName.Text;
            followup.followupTimestamp = controller.ConvertDate(txtFollowupDate.Text);
            followup.followupDiscription = txtFollowupDiscrip.Text;
            followup.followupSequenceNumber = txtSquNumber.Text;
            followup.followupAuth = txtFollowUpAuth.Text;
            return followup;
        }

        void BindFollowupCatalog(Order order = null)
        {
            int orderID = int.Parse(hdfOrderNo.Value);
            if (order == null)
                order = controller.SelectFullOrderInfo(orderID);

            txtClassificationNumber.Text = order.orderClassificationNumber;
            txtPersonName.Text = order.personName;


            DataTable customDt = new DataTable();

            DataTable instructionDt = controller.ListInstructionsForOrder(order.orderID);
            if (instructionDt == null)
            {
                lblMessage.Text = Messages.GeneralError;
                lblMessage.CssClass = "error";
                return;
            }

            DataTable followupDt = controller.ListFollowupsForOrder(order.orderID);

            DataColumn clm = new DataColumn("Type");
            clm.DefaultValue = "Instruction";
            instructionDt.Columns.Add(clm);

            customDt = instructionDt.Clone();

            if (followupDt != null)
            {
                clm = new DataColumn("Type");
                clm.DefaultValue = "Followup";
                followupDt.Columns.Add(clm);
                customDt.Merge(followupDt.Clone());
            }

            customDt.Rows.Clear();

            for (int i = 0; i < instructionDt.Rows.Count; i++)
            {
                customDt.ImportRow(instructionDt.Rows[i]);
                if (i < followupDt.Rows.Count)
                    customDt.ImportRow(followupDt.Rows[i]);
            }

            mView.ActiveViewIndex = 1;
            if (customDt.Rows[customDt.Rows.Count - 1]["Type"].ToString() == "Instruction")
            {
                mFollowup.ActiveViewIndex = 0;
            }
            else
            {
                mFollowup.ActiveViewIndex = 1;
            }
            ClearInputs();
            rptFollowupdCatalog.DataSource = customDt;
            rptFollowupdCatalog.DataBind();
        }

        private void ClearInputs()
        {
            txtFollowUpAuth.Text = "";
            txtSquNumber.Text = "";
            txtFollowupDiscrip.Text = "";
            txtFollowerName.Text = "";
            txtFollowupDate.Text = "";
            txtAuthorityOf.Text = "";
            txtForwardDate.Text = "";
            txtInstruction.Text = "";
        }

        bool UpdateOrderState(OrderStates state, int orderID)
        {
            //Update order state
            bool result = controller.UpdateOrderStates(orderID, state, user.userID);
            if (result)
            {
                txtOrderNumberToSearch.Text = "";
                BindFollowupCatalog();
            }
            return result;
        }

        #endregion

        protected void btnFollowupDoc_Click(object sender, EventArgs e)
        {
            string uploadFolder = ConfigurationManager.AppSettings["UploadPath"].ToString();
            if (string.IsNullOrEmpty(uploadFolder))
            {
                lblMessage.Text = Messages.UploadFolderNotDefined;
                lblMessage.CssClass = "error";
                return;
            }
            string uploadFolderPath = Server.MapPath(uploadFolder) + "\\";
            string fullPath = string.Empty;
            string newFileName = string.Empty;
            string dublicateNewFileName = string.Empty;

            if (!fuFollowupDoc.HasFile)
            {
                //lblUploadMessage.Text = Messages.UploadNoFile;
                //lblUploadMessage.CssClass = "error";
                return;
            }
            try
            {
                newFileName = hdfOrderNo.Value + Path.GetExtension(fuFollowupDoc.FileName);
                newFileName = AttachmentsType.OrderFollowUp.ToString() + "-" + newFileName;
                fullPath = uploadFolderPath + newFileName;
                int count = 0;
                while (File.Exists(fullPath))
                {
                    count++;
                    dublicateNewFileName = "({0})" + newFileName;
                    dublicateNewFileName = string.Format(dublicateNewFileName, count.ToString());
                    fullPath = uploadFolderPath + dublicateNewFileName;
                }

                fuFollowupDoc.PostedFile.SaveAs(fullPath);
            }
            catch (Exception)
            {
                throw;
            }
            if (!string.IsNullOrEmpty(dublicateNewFileName))
                newFileName = dublicateNewFileName;
            bool result = controller.AddAttachmentToOrder(int.Parse(hdfOrderNo.Value), newFileName, (int)AttachmentsType.OrderFollowUp, user.userID);

            if (!result)
            {
                //lblUploadMessage.Text = Messages.UploadFail;
                //lblUploadMessage.CssClass = "error";
                return;
            }
        }
    }
}